package com.xxxx.server.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.xxxx.server.pojo.AttdRecord;
import com.xxxx.server.pojo.MailConstants;
import com.xxxx.server.pojo.MailLog;
import com.xxxx.server.service.IAttdRecordService;
import com.xxxx.server.service.IMailLogService;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 邮件发送定时任务
 *
 * @author: STFU
 * @create: 2021-04-08
 **/
@Component
public class MailTask {

    @Autowired
    private IMailLogService mailLogService;
    @Autowired
    private IAttdRecordService attdRecordService;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    //邮件发送定时任务 10s执行一次
    @Scheduled(cron = "0 */10 * * * ?")
    public void mailTask(){
        List<MailLog> list = mailLogService.list(new QueryWrapper<MailLog>()
                .eq("status", 0)
                .lt("try_time", LocalDateTime.now()));
        list.forEach(mailLog -> {
            //如果重试次数超过3次,更新状态为投递失败，不再重试
            if (3 <= mailLog.getCount()){
                mailLogService.update(new UpdateWrapper<MailLog>()
                        .set("status",2)
                        .eq("msg_id",mailLog.getMsgId()));
            }
            mailLogService.update(new UpdateWrapper<MailLog>().set("count", mailLog.getCount()+1)
                    .set("update_time", LocalDateTime.now())
                    .set("try_time",LocalDateTime.now().plusMinutes(MailConstants.MSG_TIMEOUT))
                    .eq("msg_id",mailLog.getMsgId()));
            AttdRecord leave = attdRecordService.getLeaveById(mailLog.getLeaveId());
            rabbitTemplate.convertAndSend(MailConstants.MAIL_EXCHANGE_NAME,
                    MailConstants.MAIL_ROUTING_KEY_NAME, leave, new CorrelationData(mailLog.getMsgId()));
        });
    }

}
